package com.lmm.lcuser.lc_user;

import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

import com.baidu.mapapi.map.BaiduMap;
import com.brentvatne.react.ReactVideoPackage;
import com.facebook.react.ReactPackage;
import com.facebook.react.bridge.Arguments;
import com.facebook.react.bridge.Callback;
import com.facebook.react.bridge.WritableMap;
import com.jph.takephoto.app.TakePhoto;
import com.jph.takephoto.app.TakePhotoImpl;
import com.jph.takephoto.compress.CompressConfig;
import com.jph.takephoto.model.CropOptions;
import com.jph.takephoto.model.InvokeParam;
import com.jph.takephoto.model.TContextWrap;
import com.jph.takephoto.model.TImage;
import com.jph.takephoto.model.TResult;
import com.jph.takephoto.permission.InvokeListener;
import com.jph.takephoto.permission.PermissionManager;
import com.jph.takephoto.permission.TakePhotoInvocationHandler;
import com.lmm.dresswisdom.lmmframe.base.BaseCompatActivity;
import com.lmm.dresswisdom.lmmframe.components.alert.AlertUtils;
import com.lmm.dresswisdom.lmmframe.components.dialog.DefaultWaitDialog;
import com.lmm.dresswisdom.lmmframe.reactnative.BaseRNActivity;
import com.lmm.dresswisdom.lmmframe.reactnative.RNJsBridgeCallAction;
import com.lmm.dresswisdom.lmmframe.reactnative.RNJsBridgeManager;
import com.lmm.dresswisdom.lmmframe.util.LogUtils;
import com.lmm.dresswisdom.lmmframe.util.ToastUtils;
import com.lmm.lcuser.lc_user.plugins.ChangeCityPlugin;
import com.lmm.lcuser.lc_user.plugins.CheckCityPlugin;
import com.lmm.lcuser.lc_user.plugins.ChooseMapLocationPlugin;
import com.lmm.lcuser.lc_user.plugins.ChoosePlacePlugin;
import com.lmm.lcuser.lc_user.plugins.GetConfigvaluePlugin;
import com.lmm.lcuser.lc_user.plugins.GetGoodsCategoryPlugin;
import com.lmm.lcuser.lc_user.plugins.GetLocationPlugins;
import com.lmm.lcuser.lc_user.plugins.GetLogCategoryPlugin;
import com.lmm.lcuser.lc_user.plugins.HideLoadingPlugin;
import com.lmm.lcuser.lc_user.plugins.NaviPlugin;
import com.lmm.lcuser.lc_user.plugins.SetConfigvaluePlugin;
import com.lmm.lcuser.lc_user.plugins.ShowInfoPlugin;
import com.lmm.lcuser.lc_user.plugins.ShowLoadingPlugin;
import com.lmm.lcuser.lc_user.plugins.UploadCallBack;
import com.lmm.lcuser.lc_user.rnpackages.map.BaiduMapPackage;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author xmgong
 */
public class MainActivity extends BaseRNActivity implements TakePhoto.TakeResultListener, InvokeListener {

    @Override
    public void addPlugins() {
        new GetLocationPlugins(this);
        //新注册方式
        new GetConfigvaluePlugin(this);
        new CheckCityPlugin(this);
        new ChangeCityPlugin(this);
        new NaviPlugin(this);
        new CheckCityPlugin(this);
        new ChoosePlacePlugin(this);
        new ShowLoadingPlugin(this);
        new HideLoadingPlugin(this);
        new ShowInfoPlugin(this);
        new SetConfigvaluePlugin(this);
        new GetGoodsCategoryPlugin(this);
        new GetLogCategoryPlugin(this);

        RNJsBridgeManager.get().registerAction("photoUtils", new RNJsBridgeCallAction() {
            @Override
            public void call(Map<String, Object> map, Callback callback) {
                addCallBack("photoUtils", callback);
                String type = map.get("type").toString();
                int width = (int) map.get("size_w");
                int height = (int) map.get("size_h");

                QiNiuTag = map.get("filetag").toString();
                if (QiNiuTag == null || QiNiuTag.length() == 0) {
                    QiNiuTag = "android";
                }
                QiNiuToken = map.get("token").toString();

                if (!takePhotoImgFile.getParentFile().exists()) {
                    takePhotoImgFile.getParentFile().mkdirs();
                }
                CompressImageImpl();
                if (type.equals("takephoto")) {
                    //拍照
                    if (width == 0 || height == 0) {
                        //不裁剪
                        getTakePhoto().onPickFromCapture(Uri.fromFile(takePhotoImgFile));
                    } else {
                        //裁剪
                        getTakePhoto().onPickFromCaptureWithCrop(Uri.fromFile(takePhotoImgFile),
                                new CropOptions.Builder().setAspectX(width).setAspectY(height).setWithOwnCrop(true)
                                        .create());
                    }
                } else if (type.equals("choose")) {
                    //选择相册
                    if (width == 0 || height == 0) {
                        //不裁剪
                        getTakePhoto().onPickFromGallery();
                    } else {
                        //裁剪
                        getTakePhoto().onPickFromGalleryWithCrop(Uri.fromFile(takePhotoImgFile),
                                new CropOptions.Builder().setAspectX(width).setAspectY(height).setWithOwnCrop(true)
                                        .create());
                    }
                } else {
                    ToastUtils.showToastShort("photoUtils方法中,type参数不对");
                }
            }
        });
    }

    @Override
    public String getJsRootName() {
        return "LMMAndroidApp";
    }

    @Override
    public boolean setDebug() {
        return true;
    }

    @Override
    public List<ReactPackage> setOtherPackages() {
        List<ReactPackage> res = new ArrayList<>();
        res.add(new ReactVideoPackage());
        res.add(new BaiduMapPackage(this));
        return res;
    }

    DefaultWaitDialog defaultWaitDialog;

    public void showDefaultDialog() {
        if (defaultWaitDialog == null) {
            defaultWaitDialog = new DefaultWaitDialog(this);
        }

        if (!defaultWaitDialog.isShowing()) {
            LogUtils.write("show");
            defaultWaitDialog.ShowDialog();
        }
    }

    public void hideDefaultDialog() {
        if (defaultWaitDialog == null) {
            defaultWaitDialog = new DefaultWaitDialog(this);
        }

        if (defaultWaitDialog.isShowing()) {
            LogUtils.write("hide");
            defaultWaitDialog.HideDialog();
            defaultWaitDialog = null;
        }

    }

    /**
     * 拍照
     */
    TakePhoto takePhoto;
    /**
     * 拍照后图片文件
     */
    File takePhotoImgFile;
    /**
     * 文件夹名称
     */
    String QiNiuTag = "";
    String QiNiuToken = "";
    /**
     * 图片上传后网络地址
     **/
    String picUrls = "";

    private InvokeParam invokeParam;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        getTakePhoto().onCreate(savedInstanceState);
        super.onCreate(savedInstanceState);
        takePhotoImgFile = new File(Environment.getExternalStorageDirectory(), "/temp/" + System.currentTimeMillis() + ".jpg");

        if (BuildConfig.DEBUG) {
            AlertUtils.showActionAlert(this, "调试", "是否跳转应用设置", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    toAppSetting();
                }
            }, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {

                }
            });
        }
    }


    private void toAppSetting() {
        Intent localIntent = new Intent();
        localIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        if (Build.VERSION.SDK_INT >= 9) {
            localIntent.setAction("android.settings.APPLICATION_DETAILS_SETTINGS");
            localIntent.setData(Uri.fromParts("package", getPackageName(), null));
        } else if (Build.VERSION.SDK_INT <= 8) {
            localIntent.setAction(Intent.ACTION_VIEW);
            localIntent.setClassName("com.android.settings", "com.android.settings.InstalledAppDetails");
            localIntent.putExtra("com.android.settings.ApplicationPkgName", getPackageName());
        }
        startActivity(localIntent);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        getTakePhoto().onActivityResult(requestCode, resultCode, data);
        super.onActivityResult(requestCode, resultCode, data);
    }

    private TakePhoto getTakePhoto() {
        if (takePhoto == null) {
            takePhoto = (TakePhoto) TakePhotoInvocationHandler.of(this).bind(new TakePhotoImpl(this, this));
        }
        return takePhoto;
    }

    @Override
    public void takeSuccess(final TResult result) {
        if (result.getImages().size() > 0) {
            picUrls = "";
            showDefaultDialog();
            for (TImage image : result.getImages()) {
                ReactNativePresent.uploadImg(QiNiuToken, QiNiuTag, new File(image.getOriginalPath()), new UploadCallBack() {
                    @Override
                    public void uploadFinish(String netaddress) {
                        if (result.getImages().size() > 1) {
                            picUrls += netaddress + ";";
                            if (picUrls.split(";").length == result.getImages().size()) {
                                hideDefaultDialog();
                                //开始回调
                                if (getCallBack("chooseMultiImgs") != null) {
                                    WritableMap writableMap = Arguments.createMap();
                                    writableMap.putString("imgs", picUrls);
                                    getCallBack("chooseMultiImgs").invoke(writableMap);
                                }
                            }
                        } else {
                            picUrls = netaddress;
                            hideDefaultDialog();
                            //开始回调
                            if (getCallBack("photoUtils") != null) {
                                WritableMap writableMap = Arguments.createMap();
                                writableMap.putString("imgs", picUrls);
                                getCallBack("photoUtils").invoke(writableMap);
                            }
                        }
                    }
                });
            }
        }
    }

    @Override
    public void takeFail(TResult result, String msg) {

    }

    @Override
    public void takeCancel() {
        ToastUtils.showToastShort("拍照已取消");
    }

    @Override
    public PermissionManager.TPermissionType invoke(InvokeParam invokeParam) {
        PermissionManager.TPermissionType type = PermissionManager.checkPermission(TContextWrap.of(this), invokeParam.getMethod());
        if (PermissionManager.TPermissionType.WAIT.equals(type)) {
            this.invokeParam = invokeParam;
        }
        return type;
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions,
                                           int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        PermissionManager.TPermissionType type = PermissionManager.onRequestPermissionsResult(requestCode, permissions, grantResults);
        PermissionManager.handlePermissionsResult(this, type, invokeParam, this);
    }


    public void CompressImageImpl() {
        CompressConfig config = new CompressConfig.Builder()
                .setMaxSize(50 * 1024)
                .setMaxPixel(800)
                .create();
        getTakePhoto().onEnableCompress(config, true);
    }
}
